<?php
/**
 * 蜘蛛监控插件 - 许可证服务端API
 * 作者：Eric
 * 网站：https://zibovip.top
 */

// 尝试定位并加载 WordPress；找不到则以独立模式运行
if (!defined('ABSPATH')) {
    $current = dirname(__FILE__);
    $found_wp = false;
    for ($i = 0; $i < 6; $i++) { // 向上最多 6 层
        if (file_exists($current . '/wp-load.php')) {
            define('ABSPATH', rtrim($current, '/') . '/');
            require_once(ABSPATH . 'wp-load.php');
            $found_wp = true;
            break;
        }
        $current = dirname($current);
    }
    if (!$found_wp) {
        // 独立模式：不依赖 WordPress，仅依赖本地 license-functions.php
        define('ABSPATH', dirname(__FILE__) . '/');
    }
}

class Spider_License_API_Service {
    
    public function activate_license($license_key, $domain, $ip_address = '', $user_agent = '', $access_token = '', $token_expires_at = '', $token_meta = '') {
        require_once(dirname(__FILE__) . '/license-functions.php');
        
        $result = spider_activate_license($license_key, $domain, $ip_address, $user_agent, $access_token, $token_expires_at, $token_meta);
        
        if (function_exists('is_wp_error') && is_wp_error($result)) {
            return array('success' => false, 'message' => $result->get_error_message());
        }
        
        return $result;
    }
    
    public function verify_license($license_key, $domain) {
        require_once(dirname(__FILE__) . '/license-functions.php');
        
        $result = spider_verify_license($license_key, $domain);
        
        if (function_exists('is_wp_error') && is_wp_error($result)) {
            return array('success' => false, 'message' => $result->get_error_message());
        }
        
        return $result;
    }
    
    public function deactivate_license($license_key, $domain) {
        require_once(dirname(__FILE__) . '/license-functions.php');
        
        $result = spider_deactivate_license($license_key, $domain);
        
        if (function_exists('is_wp_error') && is_wp_error($result)) {
            return array('success' => false, 'message' => $result->get_error_message());
        }
        
        return $result;
    }
    
    public function check_feature_access($license_key, $domain, $feature) {
        require_once(dirname(__FILE__) . '/license-functions.php');
        
        $result = spider_check_feature_access($license_key, $domain, $feature);
        
        if (function_exists('is_wp_error') && is_wp_error($result)) {
            return array('success' => false, 'message' => $result->get_error_message());
        }
        
        return $result;
    }
    
    public function get_license_details($license_key, $domain = '') {
        require_once(dirname(__FILE__) . '/license-functions.php');
        
        $result = spider_get_license_details($license_key, $domain);
        
        if (is_wp_error($result)) {
            return array('success' => false, 'message' => $result->get_error_message());
        }
        
        return $result;
    }
    
    /**
     * 获取API文档
     */
    public function get_api_documentation() {
        return [
            'api' => 'Spider Monitor License API',
            'version' => '1.0.0',
            'description' => '蜘蛛监控插件许可证验证API，支持许可证激活、验证、停用和功能权限检查',
            'endpoints' => [
                'POST /dingyue/license-api.php' => [
                    'action=activate' => '激活许可证',
                    'action=verify' => '验证许可证',
                    'action=deactivate' => '停用许可证',
                    'action=check-feature' => '检查功能权限',
                    'action=docs' => '获取API文档'
                ]
            ],
            'parameters' => [
                'license_key' => [
                    'type' => 'string',
                    'required' => true,
                    'description' => '许可证密钥，格式：XXXXX-XXXXX-XXXXX-XXXXX-XXXXX'
                ],
                'domain' => [
                    'type' => 'string',
                    'required' => true,
                    'description' => '激活域名，如：example.com'
                ],
                'ip' => [
                    'type' => 'string',
                    'required' => false,
                    'description' => '客户端IP地址，默认自动获取'
                ],
                'user_agent' => [
                    'type' => 'string',
                    'required' => false,
                    'description' => '用户代理字符串，默认自动获取'
                ],
                'feature' => [
                    'type' => 'string',
                    'required' => false,
                    'description' => '功能名称，如：basic_stats, advanced_analytics'
                ]
            ],
            'response_format' => [
                'success' => 'boolean, 操作是否成功',
                'message' => 'string, 操作结果消息',
                'data' => 'array, 返回数据（成功时）',
                'error' => 'string, 错误详情（失败时）'
            ],
            'example_usage' => [
                'activate' => 'POST /dingyue/license-api.php?action=activate&license_key=XXXXX-XXXXX-XXXXX-XXXXX-XXXXX&domain=example.com',
                'verify' => 'POST /dingyue/license-api.php?action=verify&license_key=XXXXX-XXXXX-XXXXX-XXXXX-XXXXX&domain=example.com',
                'check_feature' => 'POST /dingyue/license-api.php?action=check-feature&license_key=XXXXX-XXXXX-XXXXX-XXXXX-XXXXX&domain=example.com&feature=basic_stats',
                'docs' => 'GET /dingyue/license-api.php?action=docs'
            ],
            'features' => [
                'domain_binding' => '支持域名绑定',
                'activation_limit' => '支持激活数量限制',
                'feature_control' => '支持功能权限控制',
                'expiration_management' => '支持过期时间管理',
                'local_api' => '支持本地API调用'
            ]
        ];
    }
}

// 处理API请求
// 统一设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理 CORS 预检
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if (isset($_GET['action'])) {
    
    $service = new Spider_License_API_Service();
    $action = $_GET['action'];
    
    // GET请求处理文档获取
    if ($action === 'docs' && $_SERVER['REQUEST_METHOD'] === 'GET') {
        echo json_encode($service->get_api_documentation(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // POST请求处理其他操作
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 签名校验（若配置了共享密钥）
        $secret = function_exists('get_option') ? get_option('spider_license_shared_secret') : '';
        if (!empty($secret)) {
            $params = $_POST;
            $sig = $params['sig'] ?? '';
            unset($params['sig']);
            ksort($params);
            $payload = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
            $calc = hash_hmac('sha256', $payload, $secret);
            if (!$sig || !hash_equals($calc, $sig)) {
                echo json_encode(['success' => false, 'message' => '签名校验失败']);
                exit;
            }
        }
        switch ($action) {
            case 'activate':
                $license_key = $_POST['license_key'] ?? '';
                $domain = $_POST['domain'] ?? '';
                $ip_address = $_POST['ip'] ?? $_SERVER['REMOTE_ADDR'];
                $user_agent = $_POST['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
                $token       = $_POST['token'] ?? '';
                // 支持 token_expires_at 或 token_ttl（秒）两种传参
                $token_expires_at = $_POST['token_expires_at'] ?? '';
                if (empty($token_expires_at) && isset($_POST['token_ttl'])) {
                    $ttl = intval($_POST['token_ttl']);
                    if ($ttl > 0) {
                        if (function_exists('current_time')) {
                            $token_expires_at = date('Y-m-d H:i:s', current_time('timestamp') + $ttl);
                        } else {
                            $token_expires_at = date('Y-m-d H:i:s', time() + $ttl);
                        }
                    }
                }
                $token_meta  = $_POST['token_meta'] ?? '';
                
                if (empty($license_key) || empty($domain)) {
                    echo json_encode(['success' => false, 'message' => '缺少必要参数']);
                    exit;
                }
                
                $result = $service->activate_license($license_key, $domain, $ip_address, $user_agent, $token, $token_expires_at, $token_meta);
                echo json_encode($result);
                exit;
                
            case 'verify':
                $license_key = $_POST['license_key'] ?? '';
                $domain = $_POST['domain'] ?? '';
                
                if (empty($license_key) || empty($domain)) {
                    echo json_encode(['success' => false, 'message' => '缺少必要参数']);
                    exit;
                }
                
                $result = $service->verify_license($license_key, $domain);
                // 同步更新 last_check 与域名状态（若存在表字段）
                if (!empty($result['success'])) {
                    global $wpdb;
                    $activations_table = $wpdb->prefix . 'spider_license_activations';
                    if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$activations_table} LIKE 'last_check'"))) {
                        $wpdb->query($wpdb->prepare("UPDATE {$activations_table} SET last_check = NOW() WHERE domain = %s", $domain));
                    }
                }
                echo json_encode($result);
                exit;

            case 'activation-status':
                $domain = $_POST['domain'] ?? '';
                $license_key = $_POST['license_key'] ?? '';
                if (empty($domain)) {
                    echo json_encode(['success' => false, 'message' => '缺少域名']);
                    exit;
                }
                require_once(dirname(__FILE__) . '/license-functions.php');
                $status = spider_get_activation_status($domain, $license_key);
                echo json_encode($status);
                exit;
                
            case 'deactivate':
                $license_key = $_POST['license_key'] ?? '';
                $domain = $_POST['domain'] ?? '';
                
                if (empty($license_key) || empty($domain)) {
                    echo json_encode(['success' => false, 'message' => '缺少必要参数']);
                    exit;
                }
                
                $result = $service->deactivate_license($license_key, $domain);
                echo json_encode($result);
                exit;
                
            case 'check-feature':
                $license_key = $_POST['license_key'] ?? '';
                $domain = $_POST['domain'] ?? '';
                $feature = $_POST['feature'] ?? '';
                
                if (empty($license_key) || empty($domain) || empty($feature)) {
                    echo json_encode(['success' => false, 'message' => '缺少必要参数']);
                    exit;
                }
                
                $result = $service->check_feature_access($license_key, $domain, $feature);
                echo json_encode($result);
                exit;
                
            default:
                echo json_encode(['success' => false, 'message' => '无效的操作']);
                exit;
        }
    }
    
    // 处理GET请求的其他操作
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        switch ($action) {
            case 'details':
                $license_key = $_GET['license_key'] ?? '';
                $domain = $_GET['domain'] ?? '';
                
                if (empty($license_key)) {
                    echo json_encode(['success' => false, 'message' => '缺少许可证密钥']);
                    exit;
                }
                
                $result = $service->get_license_details($license_key, $domain);
                echo json_encode($result);
                exit;
                
            default:
                echo json_encode(['success' => false, 'message' => '无效的操作']);
                exit;
        }
    }
}

// 未提供 action 时，返回 docs 以便直接测试
echo json_encode((new Spider_License_API_Service())->get_api_documentation(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
?>